#include"SongItem.h" 

#include"Song.h"

SongItem::SongItem(QPointer<Song> song, QListWidget* parent):QListWidgetItem(parent, QListWidgetItem::UserType){
	m_rank = 0;
	m_song = song;
	if(!m_song->isValid()){
		QListWidgetItem::setData( Qt::DisplayRole, m_song->path() );
		return;
	}
	
	int fullDisplay = 2;
	int row = ((QListWidget*)parent)->row(this);
	SongItem *prev = 0;
	if(row > 0){
		prev = (SongItem*) ((QListWidget*)parent)->item(row-1);
		if(song->album() == prev->song()->album())
			fullDisplay = 0;
		else if(song->artist() == prev->song()->artist())
			fullDisplay = 1;
	}
	
	setData(fullDisplay);
}

void SongItem::setData(short int rank){
	if(rank < 0)
		rank = m_rank;
	else
		m_rank = rank;
	if(!m_song)
		return;
	
	switch(rank){
		case 0:
			QListWidgetItem::setData( Qt::DisplayRole, QString().setNum(m_song->track()) + " - " + m_song->title() );
			break;
		case 1:
			QListWidgetItem::setData( Qt::DisplayRole, m_song->album() + "\n" + QString().setNum(m_song->track()) + " - " + m_song->title() );
			break;
		case 2:
			QListWidgetItem::setData( Qt::DisplayRole, m_song->artist() + "\n" + m_song->album() + "\n" + QString().setNum(m_song->track()) + " - " + m_song->title() );
			break;
	}
	QListWidgetItem::setData( Qt::DecorationRole, QVariant( QIcon::fromTheme("audio-x-generic") ) );
	if(m_song->title().isEmpty())
		QListWidgetItem::setData( Qt::ToolTipRole, QVariant(m_song->path()) );
	else
		QListWidgetItem::setData( Qt::ToolTipRole, QVariant(m_song->title() + "\nBy: " + m_song->artist() + "\nOn: " + m_song->album()) );
}

void SongItem::songDeleted(){
	m_song = 0;
}

SongItem::~SongItem(){
	m_song = 0;//Deleted by playlistview.
}

void SongItem::highlight(bool shouldHighlight, bool stop){
	if(shouldHighlight){
		listWidget()->scrollToItem(this);
		if(!stop)
			setIcon(QIcon::fromTheme("media-playback-start"));
		else
			setIcon(QIcon::fromTheme("media-playback-stop"));
	}else{
		setIcon(QIcon::fromTheme("audio-x-generic"));
	}
	QFont newFont = font();
	newFont.setItalic(shouldHighlight);
	setFont(newFont);
	setSelected(shouldHighlight);
}
#include<stdio.h>
void SongItem::reloadMetaData(){
	QPointer<Song> song = 0;
	try{
		song = new Song(m_song->path());
	}catch(SongException e){
		printf("Couldn't reload meta data\n");
		e.print();
		return;
	}
	m_song->apply(song);
	delete song;
	setData(-1);
}
